<?php
namespace removeData\command;
use removeData\Myprocess;
use removeData\lib\Rconfig;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\facade\Cache;
/**
 * Created by PhpStorm.
 * User: Xgh
 * Date: 2020/12/28
 * Time: 15:23
 */
class InsertData extends Command
{
    protected function configure()
    {
        $this->setName('insertdata')
            ->addArgument('i', Argument::OPTIONAL, "i");
    }

    protected function execute(Input $input, Output $output)
    {
        try{
            //源数据
            $my_process = new Myprocess();
            $i  = $input->getArguments()['i'];
            $origin_data = $my_process->data($i);

            //多表插入
            array_walk(Rconfig::$config['import_database'],function($field, $table) use($origin_data,$my_process){
                try{
                    //需要导入的数据字段
                    $fields = is_string($field) ? implode(',',$field) : $field;
                    //过滤数据
                    $insertdata = array_reduce($origin_data,function($carry,$item) use($origin_data,$fields){
                        $need_fields = array_fill_keys($fields,0);
                        $carry[] = array_intersect_key($item,$need_fields);
                        return $carry;
                    },[]);
                    $my_process->engine->newQuery()->table($table)->data($insertdata)->insertAll();

                }catch(\Exception $e){
                    trace($e->getMessage(),'debug');

                }
            });
            //需要依赖redis进行迁移
            Cache::Incrby('insert_page',1);
        }catch(\Exception $e){
            trace($e->getMessage(),'debug');
        }



    }

}